<?php

namespace App\Models;


use Illuminate\Support\Facades\DB;

class Goods extends Base
{

    // 用户管理
    protected $table = 'goods';

    // 缓存字段，用于搜索绑定的字段
    protected $cacheFields = ['id', 'uid', 'cate_id', 'verify', 'status', 'is_short_sale', 'is_start',];


    // 获取图片
    public function getImagesAttribute($value)
    {
        $images = json_decode($value, true);
        if(empty($images)){
            return [];
        }

        $res = [];
        foreach($images as $img){
            $res[] = $this->replaceDomain($img, 'full');
        }

        return $res;
    }

    // 保存图片
    public function setImagesAttribute($value)
    {
        if(is_string($value)){
            $value = json_decode($value, true);
        }

        $res = [];
        foreach($value as $img){
            $res[] = $this->replaceDomain($img, 'old');
        }

        return json_encode($res);
    }


    // 获取图片
    public function getContentAttribute($value)
    {
        return $this->replaceDomain($value, 'full');
    }

    // 保存图片
    public function setContentAttribute($value)
    {
        return $this->replaceDomain($value, 'old');
    }

    // 保存图片
    public function getSizeAttribute($value)
    {
        return json_decode($value, true) ?? [];
    }

    // 保存图片
    public function getColorAttribute($value)
    {
        return json_decode($value, true) ?? [];
    }

    // 添加
    public function oneAdd($data = [])
    {
        // 模型数据
        $descDb = new GoodsDesc();
        $goods  = $this->filterField($data);
        $desc   = $descDb->filterField($data);
        $this->fill($goods);

        // 保存数据
        DB::beginTransaction();
        try{

            // 添加
            $this->save();
            $gId = $this->id;

            // 附表
            $desc['goods_id'] = $gId;
            $descDb->fill($desc);
            $descDb->save();

            DB::commit();
        } catch(\Exception $e){
            DB::rollBack();

            return $this->return_false($e->getMessage());
        }

        // 缓存操作
        $this->deleteCacheShow($data);

        return $gId;
    }


    // 修改
    // TODO 栏目话题可以是多个的数组，也可以是单个字符串（不能是多个组合的字符串）
    public function oneEdit($where, $data)
    {
        // 查询
        $info = $this->where($where)->first();  // ->recycle()
        if(empty($info)){
            return $this->return_false('你要修改的数据不存在！！');
        }

        $info = is_object($info) ? $info->toArray() : $info;
        $g_id = $info['id'];

        // 数据
        $descDb = new GoodsDesc();
        $goods  = $this->filterField($data);
        $desc   = $descDb->filterField($data);
        if($desc){
            $descInfo = $descDb->where('goods_id', $g_id)->first();
        }
        unset($goods['id'], $goods['goods_id']);
        // 保存数据
        DB::beginTransaction();
        try{
            // 主表
            $result = $this->newQuery()->where('id', $g_id)->update($goods);
            if($desc){
                $result = $descDb->newQuery()->where('goods_id', $g_id)->update($desc);
            }


            DB::commit();
        } catch(\Exception $e){
            DB::rollBack();

            return $this->return_false($e->getMessage());
        }

        // 缓存操作
        $this->deleteCacheShow($info, $data);
        $descDb->deleteCacheShow($desc, $descInfo ?? []);

        return $result;
    }


    // 定义验证操作
    public function rules()
    {

        $add = [
        ];

        $edit = [
        ];

        $info = [
        ];


        $rule = [
            // 详情
            // 'content'     => 'required',

            'title'        => 'required',
            'from_channel' => 'sometimes|required',
            'site_id'      => 'required',
            'from_site'    => 'required',
            'description'  => 'required',
            'from_url'     => 'required',
            'author'       => 'sometimes|required',
            //'keyword'     => 'required',
            'push_time'    => 'sometimes|required',
            'cover'        => 'sometimes|required',
            'uid'          => 'numeric',
            'cate_id'      => 'numeric',
            'read_no'      => 'numeric',
            'virtual_no'   => 'numeric',
            'praise_no'    => 'numeric',
            'collect_no'   => 'numeric',
            'relay_no'     => 'numeric',
            'comment_no'   => 'numeric',
            'is_top'       => 'numeric',
            'verify'       => ['in:0,1'],
            //'status'      => ['in:0,1,2'],
            //'is_original' => 'numeric',
            //'images'      => 'required',
        ];


        $msg = [
            'id'           => '自编号',
            'title'        => '标题',
            'uid'          => '用户id',
            'cover'        => '图片',
            'cate_id'      => '栏目id',
            'author'       => '作家',
            'site_id'      => '来源站点id',
            'from_site'    => '来源站点',
            'from_channel' => '来源频道',
            'keyword'      => '关键字',
            'description'  => '描述(现在快讯最多588个字)',
            'read_no'      => '浏览数',
            'virtual_no'   => '虚拟浏览数',
            'praise_no'    => '点赞数',
            'collect_no'   => '收藏数',
            'relay_no'     => '转发次数',
            'comment_no'   => '评论次数',
            'images'       => '图片集合',
            'verify'       => '是否审核（1-是，-1删除）',
            'ip'           => 'ip地址',
            'ip_address'   => 'ip的实际地址',
            'is_top'       => '是否置顶（1-是）',
            'is_push'      => '是否推送（1-是）',
            'from_url'     => '采集文章的来源地址',
            'push_time'    => '发布时间',
            'ctime'        => '创建时间',
            'mtime'        => '修改时间',
        ];

        return ['rule' => $rule, 'msg' => $msg, 'add' => $add];
    }

}
